package com.toolkit.module.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.toolkit.module.category.bean.ApplicationCategory;
import com.toolkit.module.category.dto.ApplicationCategoryDto;
import com.toolkit.module.category.mapper.ApplicationCategoryMapper;
import com.toolkit.module.category.service.IApplicationCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Maoco
 * @since 2025-05-23
 */
@Service
public class ApplicationCategoryServiceImpl extends ServiceImpl<ApplicationCategoryMapper, ApplicationCategory> implements IApplicationCategoryService {
    @Autowired
    private ApplicationCategoryMapper applicationCategoryMapper;
    @Override
    public List<ApplicationCategoryDto> getCategoryList() {
        //校验推过来的公司ID
        QueryWrapper<ApplicationCategory> applicationCategoryQueryWrapper = new QueryWrapper<>();
        applicationCategoryQueryWrapper.orderByAsc("sort_num");
        List<ApplicationCategory> applicationCategoryList=applicationCategoryMapper.selectList(applicationCategoryQueryWrapper);
        List<ApplicationCategoryDto> applicationCategoryDtoList=list2Tree(applicationCategoryList);
        return applicationCategoryDtoList;
    }


    private List<ApplicationCategoryDto> list2Tree(List<ApplicationCategory> treeList) {
        List<ApplicationCategoryDto> retList = new ArrayList<>();
        for (ApplicationCategory parent : treeList) {
            if (parent.getParentId() == null) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }

    private ApplicationCategoryDto findChildren(ApplicationCategory parent, List<ApplicationCategory> treeList) {
        ApplicationCategoryDto parentDto = new ApplicationCategoryDto();
        parentDto.setApplicationCategory(parent);
        List<ApplicationCategory> children = new ArrayList<>();
        for (ApplicationCategory child : treeList) {
            if(child.getParentId() != null && child.getParentId()== parent.getId()){
                children.add(child);
            }
        }
        parentDto.setChild(children);
        return parentDto;
    }

}
